package com.my.core.util.img;

import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;

/**
 * @author lhp 图片预处理工具类
 */
@Slf4j
public class PreprocessImageUtils {

    public static BufferedImage loadImage(String filePath) throws IOException {
        // 读取本地文件中的验证码图片
        File file = new File(filePath);
        return ImageIO.read(file);
    }

    public static BufferedImage convertBytesToBufferedImage(byte[] imageBytes) throws IOException {
        ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
        return ImageIO.read(bis);
    }

    /**
     * 去除图片干扰
     * @param image BufferedImage
     * @return BufferedImage
     */
    public static BufferedImage preprocessImage(BufferedImage image) {
        // 读取图像
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {

                // 获取当前像素的颜色
                int argb = image.getRGB(x, y);
                Color color = new Color(argb, true);

                // 获取 RGB 值
                int red = color.getRed();
                int green = color.getGreen();
                int blue = color.getBlue();

                // 判断是否为黑色（这里简单认为 RGB 都接近 0 为黑色）
                if ((red == green && red == blue && red != 255) || (red < 35 && green < 35 && blue < 35)) {
                    // 如果是黑色，将其转换为白色
                    image.setRGB(x, y, Color.WHITE.getRGB());
                } else {
                    // 判断是否为浅灰色
                    int gray = (red + green + blue) / 3;
                    int diff = Math.max(Math.max(red - gray, green - gray), blue - gray);
                    if (gray > 200 && diff < 20) {
                        // 如果是浅灰色，将其设置为白色
                        image.setRGB(x, y, Color.WHITE.getRGB());
                    } else {
                        image.setRGB(x, y, Color.BLACK.getRGB());
                    }
                }

            }
        }
        return image;
    }

}

